<template>
  <div>
    <el-row :gutter="10" class="containerView">
      <!--table-->
      <el-col :span="24" :xs="24" class="mainHeight">
        <el-card shadow="always" class="mainHeight">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="" prop="keyword">
              <!-- <el-select
                @change="changeSelectHandle"
                v-model="queryParams.senseId"
                placeholder="请选择所属区域"
              >
                <el-option
                  v-for="item in senceList"
                  :key="item.senseId"
                  :label="item.name"
                  :value="item.senseId"
                >
                </el-option>
              </el-select> -->
            </el-form-item>

            <el-form-item style="float: right">
              <el-button
                @click="reset"
                plain
                icon="el-icon-refresh"
                size="small"
                >刷新</el-button
              >
              <el-button
                @click="addHandle"
                type="primary"
                size="small"
                icon="el-icon-plus"
                >添加</el-button
              >
            </el-form-item>
          </el-form>

          <el-table
            v-loading="loading"
            :data="tableList"
            height="70vh"
            style="width: 100%"
            default-expand-all
          >
            <el-table-column
              label="文章编号"
              prop="id"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="文章标题"
              prop="title"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="文章分类"
              prop="article_category"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.article_category">
                  {{ scope.row.article_category.name }}
                </span>
                <span v-else> --- </span>
              </template>
            </el-table-column>
            <el-table-column
              label="文章封面图"
              prop="cover_image"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <el-image
                  :src="scope.row.cover_image.url"
                  :preview-src-list="[scope.row.cover_image.url]"
                  fit="contain"
                  style="width: 80px; height: 80px"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="文章简介"
              prop="intro"
              :show-overflow-tooltip="true"
            >
            </el-table-column>

            <el-table-column
              label="创建时间"
              prop="created_at"
              :show-overflow-tooltip="true"
            ></el-table-column>

            <el-table-column
              width="200"
              label="操作"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="updateHandle(scope.row)"
                  >编辑</el-button
                >

                <el-button
                  class="text-danger"
                  type="text"
                  size="mini"
                  @click="deleteHandle(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.page"
            :limit.sync="queryParams.page_size"
            @pagination="getSuppliersListHandle"
          />
        </el-card>
        <el-dialog
          :title="editShow ? '编辑文章' : '添加文章'"
          :visible.sync="dialogVisible"
          :close-on-click-modal="false"
          destroy-on-close
          width="800px"
        >
          <el-form
            :rules="formRules"
            ref="elForm"
            :model="formData"
            class="my-form"
            size="medium"
            label-width="100px"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="文章分类" prop="article_category_id">
                  <el-select
                    v-model="formData.article_category_id"
                    placeholder="请选择文章分类"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in categoriesList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="文章封面图" prop="cover_image">
                  <el-upload
                    action="http://159.75.206.139:81/common/uploads/file"
                    :headers="header"
                    :on-success="handleAvatarSuccess"
                    :show-file-list="false"
                  >
                    <el-image
                      v-if="formData.cover_image.url"
                      :src="formData.cover_image.url"
                      fit="contain"
                      style="width: 100px; height: 100px"
                    />
                    <el-button slot="trigger" size="small" type="primary"
                      >点击上传</el-button
                    >
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="文章标题" prop="title">
                  <el-input
                    v-model="formData.title"
                    placeholder="请输入文章标题"
                    clearable
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="文章简介" prop="intro">
                  <el-input
                    v-model="formData.intro"
                    placeholder="请输入文章简介"
                    clearable
                    style="width: 100%"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="文章内容" prop="description">
                  <quill-editor
                    v-model="formData.description"
                    ref="myQuillEditor"
                    :options="editorOption"
                  >
                  </quill-editor>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button size="small" @click="dialogVisible = false"
              >取消</el-button
            >
            <el-button size="small" type="primary" @click="addCardStylesHandle"
              >确定</el-button
            >
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import {
  suppliersList,
  suppliersSourcesList,
  suppliersCategoriesList,
  suppliersStatusesList,
  addSuppliers,
  editSuppliers,
  delSuppliers,
  getContactsList,
  addContacts,
  editContacts,
  delContacts,
  invoiceSubjects,
  addInvoiceSubjects,
  editInvoiceSubjects,
  delInvoiceSubjects,
} from "@/api/suppliers";
import { getJobPositionsList } from "@/api/system/position";
import { getToken } from "@/utils/auth";
export default {
  name: "Customer",
  components: {
    quillEditor,
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    },
  },
  data() {
    return {
      filterText: "",
      // 遮罩层
      loading: false,
      showSearch: true,
      editorOption: {
        placeholder: "请输入文章内容",
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"],
            ["blockquote", "code-block"],
            [{ header: 1 }, { header: 2 }],
            [{ list: "ordered" }, { list: "bullet" }],
            [{ indent: "-1" }, { indent: "+1" }],
            ["image"],
          ],
        },
      },

      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 15,
      },

      tableList: [],
      senceList: [],
      areaList: [],
      editShow: false,
      formData: {
        id: "",
        article_category_id: "",
        cover_image: {},
        title: "",
        intro: "",
        description: "",
      },

      formRules: {
        article_category_id: [
          { required: true, trigger: "blur", message: "请选择文章分类" },
        ],
        cover_image: [
          { required: true, trigger: "blur", message: "请选择封面图片" },
        ],
        title: [{ required: true, trigger: "blur", message: "请输入标题" }],
        intro: [{ required: true, trigger: "blur", message: "请输入简介" }],
        description: [
          { required: true, trigger: "blur", message: "请输入内容" },
        ],
      },
      dialogVisible: false,
      updateShow: false,

      newAreaList: [],
      ruleLoading: false,
      actionUrl: "",
      header: {
        Authorization: "Bearer " + getToken(),
      },
      statusList: [],
      sourceList: [],
      categoriesList: [],
      contactsList: [],
      contactsDialogVisible: false,

      contactsAddDialogVisible: false,
      editContactShow: false,
      jobPositionsList: [],
      invoiceSubjectsDialogVisible: false,
      invoiceSubjectsFormData: {
        id: "",
        supplier_id: "",
        header: "",
        tax_number: "",
        bank_name: "",
        bank_account: "",
        phone: "",
        address: "",
      },
      invoiceSubjectsFormRules: {
        supplier_id: [
          { required: true, trigger: "blur", message: "请选择供应商" },
        ],
        header: [{ required: true, trigger: "blur", message: "请输入抬头" }],
        tax_number: [
          { required: true, trigger: "blur", message: "请输入税号" },
        ],
        bank_name: [
          { required: true, trigger: "blur", message: "请输入银行名称" },
        ],
        bank_account: [
          { required: true, trigger: "blur", message: "请输入银行账号" },
        ],
        phone: [{ required: true, trigger: "blur", message: "请输入手机号" }],
        address: [{ required: true, trigger: "blur", message: "请输入地址" }],
      },
      editSubjectShow: false,
      subjectsAddDialogVisible: false,
      subjectsList: [],
    };
  },
  watch: {},
  created() {
    this.getSuppliersListHandle();
    // this.suppliersStatusesListHandle();
    // this.suppliersSourcesListHandle()
    this.suppliersCategoriesListHandle();
    // this.getJobPositionsListHandle()
  },
  methods: {
    getJobPositionsListHandle() {
      getJobPositionsList().then((res) => {
        this.jobPositionsList = res.data;
      });
    },
    //点击添加联系人
    clickAddContacts() {
      this.contactsAddDialogVisible = true;
      this.contactsFormData = {
        id: "",
        supplier_id: this.contactsFormData.supplier_id,
        name: "",
        phone: "",
        address: "",
        job_position_id: "",
        is_employed: "",
        remark: "",
      };
      this.editContactShow = false;
    },
    // 编辑联系人
    addContactsHandle() {
      this.$refs.addContactForm.validate((valid) => {
        if (valid) {
          if (this.editContactShow) {
            editContacts(this.contactsFormData).then((res) => {
              this.$message.success("编辑成功");
              this.contactsAddDialogVisible = false;
              this.getContactsListHandle();
            });
          } else {
            addContacts(this.contactsFormData).then((res) => {
              this.$message.success("添加成功");
              this.contactsAddDialogVisible = false;
              this.getContactsListHandle();
            });
          }
        }
      });
    },
    //获取开票资料列表
    getInvoiceSubjectsHandle() {
      this.invoiceSubjectsDialogVisible = true;
      invoiceSubjects({
        supplier_id: this.invoiceSubjectsFormData.supplier_id,
      }).then((res) => {
        this.subjectsList = res.data;
      });
    },
    // 获取联系人列表
    getContactsListHandle() {
      getContactsList({
        supplier_id: this.contactsFormData.supplier_id,
      }).then((res) => {
        this.contactsList = res.data;
        this.contactsDialogVisible = true;
      });
    },
    clickCustomerIdHandle(row) {
      this.contactsFormData.supplier_id = row.id;
      this.getContactsListHandle();
    },
    //点击开票资料
    clickSubjectsIdHandle(row) {
      this.invoiceSubjectsFormData.supplier_id = row.id;
      this.getInvoiceSubjectsHandle();
    },
    suppliersStatusesListHandle() {
      suppliersStatusesList().then((res) => {
        this.statusList = res.data;
      });
    },
    suppliersSourcesListHandle() {
      suppliersSourcesList().then((res) => {
        this.sourceList = res.data;
      });
    },
    suppliersCategoriesListHandle() {
      suppliersCategoriesList().then((res) => {
        this.categoriesList = res.data;
      });
    },
    addCardStylesHandle() {
      this.$refs.elForm.validate((valid) => {
        if (valid) {
          if (this.editShow) {
            editSuppliers({
              id: this.formData.id,
              article_category_id: this.formData.article_category_id,
              cover_image: JSON.stringify(this.formData.cover_image),
              title: this.formData.title,
              intro: this.formData.intro,
              description: this.formData.description,
            }).then((res) => {
              this.$message.success("编辑成功");
              this.dialogVisible = false;
              this.getSuppliersListHandle();
            });
          } else {
            addSuppliers({
              article_category_id: this.formData.article_category_id,
              cover_image: JSON.stringify(this.formData.cover_image),
              title: this.formData.title,
              intro: this.formData.intro,
              description: this.formData.description,
            }).then((res) => {
              this.$message.success("添加成功");
              this.dialogVisible = false;
              this.getSuppliersListHandle();
            });
          }
        }
      });
    },
    handleAvatarSuccess(res, file) {
      let that = this;
      that.formData.cover_image = res;

      that.$refs.elForm.validateField("cover_image"); // 手动触发图片字段验证
      that.$forceUpdate(); // 强制更新视图
    },
    beforeAvatarUpload(file) {},
    getSuppliersListHandle() {
      this.loading = true;
      suppliersList(this.queryParams)
        .then((res) => {
          this.tableList = res.data;
          this.total = res.meta.total;
          this.loading = false;
          console.log(this.tableList);
        })
        .catch((error) => {
          this.loading = false;
        });
    },

    deleteHandle(row) {
      this.$modal
        .confirm("是否确认删除此条数据？")
        .then(async () => {
          const { code } = await delSuppliers({
            id: row.id,
          });
          this.$message.success("删除成功");
          this.getSuppliersListHandle();
        })
        .then(() => {})
        .catch(() => {});
    },

    updateHandle(cell) {
      let data = JSON.parse(JSON.stringify(cell));
      this.formData.id = data.id;
      this.formData.article_category_id = data.article_category?.id;
      this.formData.cover_image = data.cover_image;
      this.formData.title = data.title;
      this.formData.intro = data.intro;
      this.formData.description = data.description;
      this.editShow = true;
      this.dialogVisible = true;
    },
    addHandle() {
      this.editShow = false;
      this.dialogVisible = true;
      this.formData = {
        id: "",
        article_category_id: "",
        cover_image: "",
        title: "",
        intro: "",
        description: "",
      };
    },

    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      getCategories(6, {
        format: "tree",
      }).then((res) => {
        if (res.code == 0) {
          this.deptOptions = res.data.categories;
        }
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (this.queryParams.paper_type == data.id) {
        this.queryParams.paper_type = undefined;
      } else {
        this.queryParams.paper_type = data.id;
      }

      this.handleQuery();
    },

    // 表单重置
    reset() {
      this.queryParams = {
        page: 1,
        keyword: undefined,
        creator_id: undefined,
        status: undefined,
        tag_ids: undefined,
        paper_type: undefined,
        parentId: undefined,
      };
      this.filterText = undefined;
      this.getSuppliersListHandle();
    },

    handleDelete() {
      const ids = this.ids;
      console.log(this.ids);
      this.$modal
        .confirm('是否确认删除编号ID为"' + ids + '"的数据项？')
        .then(async () => {
          const { code } = await delPaper({
            ids: this.ids,
          });
          console.log(1);
          if (code === 0) {
            this.$message.success("删除成功");
            this.handleQuery();
          }
          // return delUser(userIds);
        })
        .then(() => {
          console.log(2);
          // this.getList();
          // this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
          console.log(3);
        });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handleImageError(event) {
      console.error("图片加载失败:", event.target.src);
      this.$message.error("图片加载失败，请检查图片地址或网络连接");
    },
  },
};
</script>
<style scoped scss>
@import url("~@/assets/styles/dialog_wangpx.scss");
.th {
  word-break: break-word;
  background-color: #f8f8f9;
  color: #515a6e;
  font-weight: 700;
  height: 40px;
  font-size: 13px;
  padding: 10px;
  box-sizing: border-box;
  border: 1px solid #dfe6ec;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: none;
}
</style>
